import requests
import execjs
import json
import re
from loguru import logger
import time
import uuid
import tracieId


class Xhs:
    def __init__(self):
        self.url = 'https://edith.xiaohongshu.com/api/sns/web/v1/homefeed'
        self.json_data = {
            'cursor_score': '',
            'num': 20,
            'refresh_type': 1,
            'note_index': 35,
            'unread_begin_note_id': '',
            'unread_end_note_id': '',
            'unread_note_count': 0,
            'category': "homefeed.food_v3",
            'search_key': '',
            'need_num': 8,
            'image_formats': [
                'jpg',
                'webp',
                'avif',
            ],
            'need_filter_image': False,
        }
        self.headers = {
            'accept': 'application/json, text/plain, */*',
            'accept-language': 'zh-CN,zh;q=0.9',
            'cache-control': 'no-cache',
            'content-type': 'application/json;charset=UTF-8',
            'origin': 'https://www.xiaohongshu.com',
            'pragma': 'no-cache',
            'priority': 'u=1, i',
            'referer': 'https://www.xiaohongshu.com/',
            'sec-ch-ua': '"Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-site',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36',
        }
        self.cookie = {
            'abRequestId': str(uuid.uuid4()),
            'webBuild': '4.34.0',
            'xsecappid': 'xhs-pc-web',
            'webId': '93d55c6bbb53bbc9ff0f1a8b1944a011',
            'websectiga': '8886be45f388a1ee7bf611a69f3e174cae48f1ea02c0f8ec3256031b8be9c7ee',
            'sec_poison_id': 'd86cb193-1662-4bb7-89af-ea183f3e433e',
            'acw_tc': '5ba61a3e2cb132c96557daad5acce55d50130b117eb57fd79c60aace4e98d419',
            'web_session': '030037a1d706231c9f061b149c214af7554287',
            'gid': 'yjydDdy0WW0jyjydDfKf0U4AqyqWjx40Eu6VAKV9huKqIf28xdujik888yKyyy28KS4jYDd4',
        }

    def get_x_s(self):
        with open('./getA1ck.js', 'r', encoding='utf-8') as f:
            jsCode = f.read()
        ctx = execjs.compile(jsCode)
        self.cookie['a1'] = ctx.call("generateLocalId")
        logger.info("a1_ck" '\t' + self.cookie['a1'])
        url_data = "url=" + re.search(r'/api.*', self.url)[0] + json.dumps(self.json_data)
        # print(url_data)
        with open('./encrypt.js', 'r', encoding='utf-8') as f:
            js_code = f.read()
        ctx = execjs.compile(js_code)
        ddd = ctx.call('getX_T', url_data, self.cookie['a1'])
        self.headers['x-t'] = str(ddd['x_t'])
        logger.info('x-t' '\t' + self.headers['x-t'])
        # print(ddd)
        return ddd['x_s']

    def get_x_s_common(self):
        with open('./x_s_common生成.js', 'r', encoding='utf-8') as f:
            js_code = f.read()
        ctx = execjs.compile(js_code)
        x_s_common = ctx.call('get_x_s_common', self.headers['x-b3-traceid'], self.headers['x-s'], self.headers['x-t'],
                              self.cookie['a1'])
        return x_s_common

    def getRequest(self):
        self.headers['x-b3-traceid'] = str(tracieId.getId())
        logger.info("x-b3-traceid" '\t' + self.headers['x-b3-traceid'])
        x_s = self.get_x_s()
        logger.info("x-s" '\r\n' + x_s)
        self.headers['x-s'] = x_s
        x_s_common = self.get_x_s_common()
        logger.info('x-s-common' '\r\n' + x_s_common)
        self.headers['x-s-common'] = x_s_common
        time.sleep(1)
        response = requests.post('https://edith.xiaohongshu.com/api/sns/web/v1/homefeed', cookies=self.cookie,
                                 headers=self.headers, json=self.json_data)
        logger.success(f"响应状态码: {response.status_code}")
        print(response.json()['data']['items'])

    def main(self):
        for page in range(15, 16):
            self.json_data['num'] = page
            self.getRequest()
            time.sleep(0.7)


if __name__ == '__main__':
    xhs = Xhs()
    xhs.main()
